package com.afly.netty.core.server;

import com.afly.netty.core.codec.DeviceDecoder;
import com.afly.netty.core.codec.DeviceEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 自定义管道
 */
@Component
public class CustomerChannelInitializer extends ChannelInitializer<SocketChannel> {

    //@Resource
    //private  CustomerServerHandler myServerHandler;
    @Resource
    private ConfigurableApplicationContext applicationContext;

    @Override
    protected void initChannel(SocketChannel channel) {
        // 基于换行符号
        // channel.pipeline().addLast(new LineBasedFrameDecoder(1024));

        // 解码转String，注意调整自己的编码格式GBK、UTF-8
//        channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));

        // 设备编码器
        channel.pipeline().addLast(new DeviceEncoder());
        // 设备解码器
        channel.pipeline().addLast(new DeviceDecoder());
        CustomerServerHandler myServerHandler = applicationContext.getBean(CustomerServerHandler.class);
        // 在管道中添加我们自己的接收数据实现方法
        channel.pipeline().addLast(myServerHandler);
    }

}
